package com.basic.system.service.impl;


import com.basic.common.constant.CommonDsConstant;
import com.basic.common.exception.Errors;
import com.basic.common.exception.business.ServerServiceException;
import com.basic.common.exception.business.ValidationException;
import com.basic.common.result.WebResult;
import com.basic.system.dao.mapper.DictionaryMapper;
import com.basic.system.dao.mapper.PageMapper;
import com.basic.system.dao.model.Dictionary;
import com.basic.system.dao.model.DictionaryExample;
import com.basic.system.domain.DictionaryBo;
import com.basic.system.domain.DictionaryInsertDto;
import com.basic.system.domain.bo.DictionarDictIdVo;
import com.basic.system.service.DictionaryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.logging.log4j.util.Strings;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class DictionaryImpl implements DictionaryService {

    private static final Logger log = LoggerFactory.getLogger(DictionaryImpl.class);

    @Autowired
    private DictionaryMapper dictionaryMapper;
    @Autowired
    private PageMapper pageMapper;

    /**
     * 插入数据
     * @param dictionaryInsertDto
     * @return
     */
    @Override
    public WebResult insertSelective(DictionaryInsertDto dictionaryInsertDto) {
        log.debug("增加字典表" + dictionaryInsertDto);
        // 验证提供的记录是否为 null，以及字典ID和代码字段是否为空。
        if (dictionaryInsertDto == null || Strings.isBlank(dictionaryInsertDto.getDictId()) || Strings.isBlank(dictionaryInsertDto.getCode())) {
            //返回请求参数错误
            log.info("请求参数错误");
            try {
                log.info(Errors.SYSTEM_REQUEST_PARAM_ERROR.msg);
                throw new ValidationException(Errors.SYSTEM_REQUEST_PARAM_ERROR);
            } finally {
                WebResult webResult=new WebResult();
                webResult.setCode(Errors.SYSTEM_REQUEST_PARAM_ERROR.code);
                webResult.setMsg(Errors.SYSTEM_REQUEST_PARAM_ERROR.msg);
                webResult.setException(Errors.SYSTEM_REQUEST_PARAM_ERROR.exception);
                webResult.setData("请求参数错误");
                return webResult;
            }
        }
        // 执行插入操作。
        Dictionary dictionary=new Dictionary();
        BeanUtils.copyProperties(dictionaryInsertDto,dictionary);
        dictionary.setCreateDate(new Date());
        dictionary.setUpdateDate(new Date());
        dictionary.setSort(CommonDsConstant.DEFAULT_SORT_VALUE);
        dictionary.setIsEnabled(CommonDsConstant.IS_ENABLED);
        dictionary.setIsRead(CommonDsConstant.IS_READ);
        int insert = dictionaryMapper.insertSelective(dictionary);
        if (insert <= 0) {
            //返回数据插入失败
            log.info("数据插入失败");
            try {
                log.info(Errors.SYSTEM_REQUEST_PARAM_ERROR.msg);
                throw new ServerServiceException(Errors.SYSTEM_INSERT_ERROR);
            } finally {
                WebResult webResult = new WebResult();
                webResult.setCode(Errors.SYSTEM_INSERT_ERROR.code);
                webResult.setMsg(Errors.SYSTEM_INSERT_ERROR.msg);
                webResult.setException(Errors.SYSTEM_INSERT_ERROR.exception);
                webResult.setData("数据插入失败");
                return webResult;
            }
        }
        return WebResult.success(insert);
    }

    /**
     * 查询返回List
     * @param dictionaryBo
     * @return
     */
    @Override
    public List<Dictionary> selectByExample(DictionaryBo dictionaryBo) {
        log.info("==========查询条件==========" + dictionaryBo);
        // 创建字典查询的示例对象。
        DictionaryExample example = new DictionaryExample();
        // 创建查询条件的 Criteria 对象。
        DictionaryExample.Criteria criteria = example.createCriteria();
        // 添加默认查询条件：启用状态为已启用且标记为已读。
        criteria.andIsEnabledEqualTo(CommonDsConstant.IS_ENABLED);
        criteria.andIsReadEqualTo(CommonDsConstant.IS_READ);
        // 根据id查询。
        if (dictionaryBo.getId() != null) {
            criteria.andIdEqualTo(dictionaryBo.getId());
        }
        //根据字典id查询
        if (Strings.isNotBlank(dictionaryBo.getDictId())){
            criteria.andDictIdEqualTo(dictionaryBo.getDictId());
        }
        //根据code查询
        if (Strings.isNotBlank(dictionaryBo.getCode())){
            criteria.andCodeEqualTo(dictionaryBo.getCode());
        }
        //value的模糊查询
        if (Strings.isNotBlank(dictionaryBo.getValue())) {
            criteria.andValueLike("%" + dictionaryBo.getValue() + "%");
        }
        //根据description查询
        if (Strings.isNotBlank(dictionaryBo.getDescription())){
            criteria.andDescriptionEqualTo("%"+dictionaryBo.getDescription()+"%");
        }
        //根据remark查询
        if (Strings.isNotBlank(dictionaryBo.getRemark())){
            criteria.andRemarkEqualTo("%" + dictionaryBo.getRemark()+ "%");
        }
        //根据codeList查询
        if (CollectionUtils.isNotEmpty(dictionaryBo.getCodeList())){
            criteria.andCodeIn(dictionaryBo.getCodeList());
        }
        //根据dictIdList查询
        if (CollectionUtils.isNotEmpty(dictionaryBo.getDictIdList())){
            criteria.andDictIdIn(dictionaryBo.getDictIdList());
        }
        //根据valueList查询
        if (CollectionUtils.isNotEmpty(dictionaryBo.getValueList())){
            criteria.andValueIn(dictionaryBo.getValueList());
        }
        //默认倒序
//        Integer sort = dictionaryBo.getSort();
//        if (sort!=null){
//            example.setOrderByClause("id" +(sort==1?"asc" :"desc"));
//        }
        String sort = dictionaryBo.isDesc() ? " asc" : " desc";
        //排序
        example.setOrderByClause("id" + sort);
        // 执行查询并返回结果集。
        List<Dictionary> dictionaries = dictionaryMapper.selectByExample(example);
        return dictionaries;
    }

    /**
     * 修改数据
     * @param record
     * @return
     */
    @Override
    public WebResult updateByPrimaryKeySelective(Dictionary record) {
        log.info("==========修改内容==========" + record);
        // 验证提供的记录是否为 null 或记录的主键为空。
        if (record == null || record.getId() == null) {
            //请求参数错误
            log.info("请求参数错误");
            try {
                log.info(Errors.SYSTEM_REQUEST_PARAM_ERROR.msg);
                throw new ValidationException(Errors.SYSTEM_REQUEST_PARAM_ERROR);
            } finally {
                WebResult webResult=new WebResult();
                webResult.setCode(Errors.SYSTEM_REQUEST_PARAM_ERROR.code);
                webResult.setMsg(Errors.SYSTEM_REQUEST_PARAM_ERROR.msg);
                webResult.setException(Errors.SYSTEM_REQUEST_PARAM_ERROR.exception);
                webResult.setData("请求参数错误");
                return webResult;
            }
        }
        //查询数据是否存在
        Dictionary dictionary = dictionaryMapper.selectByPrimaryKey(record.getId());
        if (dictionary==null){
            log.info("数据不存在");
            try {
                log.info(Errors.SYSTEM_DATA_ERROR.msg);
                throw new ValidationException(Errors.SYSTEM_DATA_ERROR);
            } finally {
                WebResult webResult=new WebResult();
                webResult.setCode(Errors.SYSTEM_DATA_ERROR.code);
                webResult.setMsg(Errors.SYSTEM_DATA_ERROR.msg);
                webResult.setException(Errors.SYSTEM_DATA_ERROR.exception);
                webResult.setData("数据不存在");
                return webResult;
            }
        }

        // 执行选择性更新操作。
        int update = dictionaryMapper.updateByPrimaryKeySelective(record);
        // 检查更新操作是否成功。
        if (update <= 0) {
            //数据更新失败
            log.info("数据更新失败");
            try {
                log.info(Errors.SYSTEM_UPDATE_ERROR.msg);
                throw new ServerServiceException(Errors.SYSTEM_UPDATE_ERROR);
            } finally {
                WebResult webResult=new WebResult();
                webResult.setCode(Errors.SYSTEM_UPDATE_ERROR.code);
                webResult.setMsg(Errors.SYSTEM_UPDATE_ERROR.msg);
                webResult.setException(Errors.SYSTEM_UPDATE_ERROR.exception);
                webResult.setData("数据更新失败");
                return webResult;
            }
        }
        return WebResult.success(update);
    }


    /**
     * 分页查询
     * @param bo
     * @return
     */
    @Override
    public PageInfo selAlarmPersonSetDetailListByPage(DictionaryBo bo) {
        log.info("==========查询条件==========" + bo);
        // 设置默认的分页页码和每页大小。
        Integer pageNum = CommonDsConstant.PAGE_NUM;
        if (bo.getPageNum() != null) {
            pageNum = bo.getPageNum();
        }
        Integer pageSize = CommonDsConstant.PAGE_SIZE;
        if (bo.getPageSize() != null) {
            pageSize = bo.getPageSize();
        }
        // 使用PageHelper工具开始分页，指定页码和每页大小。
        PageHelper.startPage(pageNum, pageSize);
        // 调用selectByExample方法查询符合条件详细列表。
        List<Dictionary> list = this.selectByExample(bo);
        // 如果查询结果为空，返回空的PageInfo对象。
        if (list == null || list.size() == 0) {
            PageInfo<Dictionary> pageInfo = new PageInfo<>();
            return pageInfo;
        }
        // 将查询结果列表封装到PageInfo对象中。
        PageInfo<Dictionary> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @Override
    public WebResult deleteList(List<Long> ids) {
        log.info("==========要删除的ids==========" + ids);
        if (ids == null || ids.equals("")) {
            log.info("请求参数错误");
            try {
                log.info(Errors.SYSTEM_REQUEST_PARAM_ERROR.msg);
                throw new ValidationException(Errors.SYSTEM_REQUEST_PARAM_ERROR);
            } finally {
                WebResult webResult=new WebResult();
                webResult.setCode(Errors.SYSTEM_REQUEST_PARAM_ERROR.code);
                webResult.setMsg(Errors.SYSTEM_REQUEST_PARAM_ERROR.msg);
                webResult.setException(Errors.SYSTEM_REQUEST_PARAM_ERROR.exception);
                webResult.setData("请求参数错误");
                return webResult;
            }
        }
        // 遍历主键列表，为每个主键设置逻辑删除的标志和更新日期
        for (Long id : ids) {
            Dictionary dictionary = dictionaryMapper.selectByPrimaryKey(id);
            if (dictionary!=null){
                dictionary.setId(id);
                dictionary.setIsEnabled(CommonDsConstant.IS_NOT_ENABLED);
                dictionary.setUpdateDate(new Date());
                // 执行批量逻辑删除操作。
                updateByPrimaryKeySelective(dictionary);
                if (updateByPrimaryKeySelective(dictionary)== null) {
                    log.info("数据删除失败");
                    try {
                        log.info(Errors.SYSTEM_DELETE_ERROR.msg);
                        throw new ServerServiceException(Errors.SYSTEM_DELETE_ERROR);
                    } finally {
                        WebResult webResult=new WebResult();
                        webResult.setCode(Errors.SYSTEM_DELETE_ERROR.code);
                        webResult.setMsg(Errors.SYSTEM_DELETE_ERROR.msg);
                        webResult.setException(Errors.SYSTEM_DELETE_ERROR.exception);
                        webResult.setData("数据删除失败");
                        return webResult;
                    }
                }
            }
        }
       return WebResult.success(ids.size());
    }

    /**
     * 根据字典id和code查询
     * @param dictionary
     * @return
     */
    @Override
    public List<Dictionary> selectListByDictIdCodeId(Dictionary dictionary) {
        //判断数据是否为空
        if (dictionary == null) {
            log.info(Errors.SYSTEM_REQUEST_PARAM_ERROR.msg);
            throw new ValidationException(Errors.SYSTEM_REQUEST_PARAM_ERROR);
        }
        String dictId = dictionary.getDictId();
        String code = dictionary.getCode();
        if (Strings.isBlank(dictId) || Strings.isBlank(code)){
            log.info(Errors.SYSTEM_REQUEST_PARAM_ERROR.msg);
            throw new ValidationException(Errors.SYSTEM_REQUEST_PARAM_ERROR);
        }
        //创建字典查询的对象
        DictionaryExample example = new DictionaryExample();
        DictionaryExample.Criteria criteria = example.createCriteria();
        //添加默认查询条件：启用状态为已启用且标记为已读。
        criteria.andIsEnabledEqualTo(CommonDsConstant.IS_ENABLED);
        criteria.andIsReadEqualTo(CommonDsConstant.IS_READ);
        //添加字典id查询条件
        criteria.andDictIdEqualTo(dictId);
        //添加code查询条件
        criteria.andCodeEqualTo(code);
        //执行并返回结果集
        List<Dictionary> dictionaries = dictionaryMapper.selectByExample(example);
        return dictionaries;
    }

    /**
     * 根据code和DictId分页查询
     * @param dictionaryBo
     * @return
     */
    @Override
    public PageInfo selectListByDictIdCodePageInfo(DictionaryBo dictionaryBo) {
        //检查数据是否为空
        if (dictionaryBo == null) {
            log.info(Errors.SYSTEM_REQUEST_PARAM_ERROR.msg);
            throw new ValidationException(Errors.SYSTEM_REQUEST_PARAM_ERROR);
        }
        //创建字典对象
        DictionaryExample example = new DictionaryExample();
        DictionaryExample.Criteria criteria = example.createCriteria();
        String dictId = dictionaryBo.getDictId();
        String code = dictionaryBo.getCode();
        //根据字典id查询
        if (Strings.isNotBlank(dictionaryBo.getDictId())) {
            criteria.andDictIdEqualTo(dictId);
        }
        //根据code查询
        if (Strings.isNotBlank(dictionaryBo.getCode())) {
            criteria.andCodeEqualTo(code);
        }
        //设置默认页数
        Integer pageNum = CommonDsConstant.PAGE_NUM;
        if (dictionaryBo.getPageNum() != null) {
            pageNum = dictionaryBo.getPageNum();
        }
        //设置默认行数
        Integer pageSize = CommonDsConstant.PAGE_SIZE;
        if (dictionaryBo.getPageSize() != null) {
            pageSize = dictionaryBo.getPageSize();
        }
        //调用分页方法
        PageHelper.startPage(pageNum, pageSize);
        List<Dictionary> list = dictionaryMapper.selectByExample(example);
        PageInfo<Dictionary> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 下拉框
     * @param dictId
     * @return
     */
    @Override
    public List<DictionarDictIdVo> getPumpStationTypes(String dictId) {
        return pageMapper.getPumpStationTypes(dictId);
    }




}
